﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using WebUI.Helper;
using System.Web.Script.Serialization;



namespace WebUI.Controllers
{
    public class FileController : Controller
    {
        private string root = "../upload";
        private JavaScriptSerializer serializer=new JavaScriptSerializer();

        [AjaxAuthorize(Roles = "普通用户,系统管理员")]
        public JsonResult LoadPageFiles(int start, string path, int limit)
        {
            bool success = false;
            int total = 0;
            string msg = "";
            path = path ?? "/";
            string sort = Request["sort"];
            sort = sort.Substring(1, sort.Length - 2);
            List<object> data = null;
            try
            {
                DirectoryInfo dir = new DirectoryInfo(Server.MapPath(root + path));
                sort = ProcessSorterString(new String[] { "filename", "modify", "size" }, sort, "it.LastWriteTime ASC");
                
                total = dir.GetFiles().Count();
                data = new List<object>(total);

                var q = dir.GetFiles().Select(m => new
                {
                    filename = m.Name,
                    modify = m.LastWriteTime,
                    size = m.Length
                }).AsQueryable().OrderBy(sort).Skip(start).Take(limit);

                foreach (var item in q)
                {
                    data.Add(new
                    {
                        path = path,
                        filename = item.filename,
                        modify = item.modify.ToString("yyyy-MM-dd hh:mm"),
                        size = item.size
                    });
                }
                success = true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return Json(new { success = success, total = total, Msg = msg, data = data }, JsonRequestBehavior.AllowGet);
        }

        [AjaxAuthorize(Roles = "普通用户,系统管理员")]
        public JsonResult Romove()
        {
            bool success = false;
            int total = 0;
            string msg = "";
            List<object> list = null;
            
            string data = Request["data"] ?? "";
            if (string.IsNullOrEmpty(data))
            {
                msg = "错误的数据交换格式";
            }
            else
            {
                try
                {
                    list = serializer.Deserialize<List<object>>(data);
                    if (list.Count > 0)
                    {
                        foreach (var item in list)
                        {
                            Dictionary<string, object> obj = (Dictionary<string, object>)item;
                            string path = Server.MapPath(root+obj["path"]+obj["filename"]);
                            FileInfo file = new FileInfo(path);
                            if (file.Exists)
                            {
                                file.Delete();
                            }    
                        }
                        
                        success = true;
                    }
                    else
                    {
                        msg = "错误的提交数据。";
                    }
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                }
            }
            return Json(new { success = success, total = total, msg = msg, data = list });
        }
        /// <summary>
        /// 处理排序字段
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="sortinfo"></param>
        /// <param name="defaultSort"></param>
        /// <returns></returns>
        private string ProcessSorterString(string[] fields, string sortinfo, string defaultSort)
        {
            string resoult = "";
            if (string.IsNullOrEmpty(sortinfo))
            {
                return defaultSort;
            }
            
            Dictionary<string, object> obj = serializer.Deserialize<Dictionary<string, object>>(sortinfo);
            string field = (string)obj["property"];
            if (fields.Contains(field))
            {
                resoult += string.Format("it.{0} {1},", field,(string)obj["direction"]=="ASC"?"":"DESC");
            }
            if (resoult.Length > 0)
                resoult = resoult.Substring(0, resoult.Length - 1);
            else
                resoult =defaultSort;
            return resoult;
        }

        [AjaxAuthorize(Roles = "普通用户,系统管理员")]
        public string Upload()
        {
            string path = Request["path"] ?? "";
            string[] filetypes = { "jpg", "gif", "png", "bmp" };
            string dir = Server.MapPath(root + path);
            if (Directory.Exists(dir))
            {
                HttpPostedFileBase file = Request.Files["Filedata"];
                string filename = file.FileName.ToLower();
                string extname = filename.Substring(filename.LastIndexOf(".") + 1, 3);
                if (file.ContentLength <= 0)
                {
                    return "不允许上传0字节文件。";
                }
                else if (file.ContentLength > 10485760)
                {
                    return "文件超过了10M。";
                }
                else if (!filetypes.Contains(extname))
                {
                    return "文件类型错误。" + extname;
                }
                else
                {
                    try
                    {
                        file.SaveAs(dir + "\\" + filename);
                        return "文件已上传。" + dir + "\\" + filename;
                    }
                    catch (Exception e)
                    {
                        return e.Message;
                    }
                }
            }
            else
            {
                return "保存目录不存在或已被删除。";
            }

        }
    }
}
